import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;


/***
 * 多人群聊天类似功能
 * @author computer
 *
 */
public class Server {

	private int port = 9527;
	
	public Server() {
		init();
	}
	
	private Vector<Socket> vs = new Vector<Socket>();
	
	private  synchronized void sendAll(String msg){
		
		PrintWriter write = null;
		
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		String date = df.format(new Date());
		try {
			for(Socket socket : vs){
				
				//把客户端发送过来的数据，在发送给所有的客户端，现在仅一个客户端
				write = new PrintWriter(socket.getOutputStream(),true);
				
				write.println(msg + " "+ date);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			
//			write.close();
			
		}
	}

	private void init(){
		
		try {
			ServerSocket server = new ServerSocket(port);
			
			Thread thread = null;
			while(true){
				System.out.println("开始监听: "+port);
				//阻塞,直到接受到请求
				Socket socket = server.accept();
				//有请求后，启动线程
				thread = new Thread(new Task(socket));
				thread.start();
				//保存已经建立的socket
				vs.add(socket);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	class Task implements Runnable{
		
		private Socket socket;
		public Task(Socket socket) {
			this.socket = socket;
		}

		@Override
		public void run() {
 
			BufferedReader reader = null;
			try {
				
					//IP地址
					System.out.println(socket.getInetAddress().getHostAddress());
					
					//接受消息
					reader = new BufferedReader(new InputStreamReader(socket.getInputStream(),"utf-8"));
					//客户端发送过来的消息
					String receive=null;
				while((receive = reader.readLine())!=null){	
					System.out.println("客户端发送过来的消息: "+receive);
					//发送给所有的客户端
					System.out.println("向所有客户端发送消息:"+receive);
					sendAll(receive);
				}
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				
				try {
//					vs.remove(socket);
//					reader.close();
//					socket.close();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

	}
	
	public static void main(String[] args) {
		
		new Server();
	}
}
